package edu.ptu.acl.config;

import edu.ptu.acl.common.MyConstants;
import edu.ptu.acl.common.ResultVO;
import edu.ptu.acl.exception.ApiException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
public class ExceptionControllerAdvice {

    //参数校验异常
    @ExceptionHandler({MethodArgumentNotValidException.class,ConstraintViolationException.class,BindException.class})
    public ResultVO MethodArgumentNotValidExceptionHandler(Exception ex) {
        String errorMsg = "参数验证错误";
        BindingResult bindingResult = null;
        if (ex instanceof BindException) {
            BindException bindException = (BindException) ex;
            bindingResult = bindException.getBindingResult();
        }
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) ex;
            bindingResult = methodArgumentNotValidException.getBindingResult();
        }
        if (ex instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) ex;
            errorMsg = constraintViolationException.getMessage();
        }
        if (bindingResult != null) {
            for (FieldError filedError : bindingResult.getFieldErrors()) {
                errorMsg = filedError.getDefaultMessage();
            }
        }
        return ResultVO.falseMessage(errorMsg);
    }

    @ExceptionHandler(ApiException.class)
    public ResultVO apiException(ApiException ex){
        return ResultVO.falseMessage(ex.getMsg());
    }

}
